package nl.cwi.arne.ui.actions;

import nl.cwi.arne.Network;
import nl.cwi.arne.diagram.part.ArneDiagramEditor;
import nl.cwi.arne.ui.ArneUIPlugin;

import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.gmf.runtime.common.core.command.CommandResult;
import org.eclipse.gmf.runtime.emf.commands.core.command.AbstractTransactionalCommand;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchSite;

/**
 * Action for clearing the activations.
 * @author Christian Krause
 */
public class ClearActivationsAction extends Action {
	
	// Action icon.
	public static ImageDescriptor ICON = ArneUIPlugin.getImageDescriptor("/icons/ClearActivations.gif");
	
	// Workbench site.
	private IWorkbenchSite site;
	
	/**
	 * Constructor.
	 */
	public ClearActivationsAction(IWorkbenchSite site) {
		String name = "Generate Activations";
		setText(name);
		setToolTipText(name);
		setImageDescriptor(ICON);
		this.site = site;
	}
	
	/*
	 * (non-Javadoc)
	 * @see org.eclipse.jface.action.Action#run()
	 */
	@Override
	public void run() {
		
		IEditorPart editor = site.getPage().getActiveEditor();
		if (editor instanceof ArneDiagramEditor) {
			
			// Ask for confirmation:
			if (!MessageDialog.openConfirm(site.getShell(), "Clear Activations", "All activations will be deleted. Continue?")) {
				return;
			}
			
			// Diagram editor and network:
			ArneDiagramEditor arneEditor = (ArneDiagramEditor) editor;
			final Network network = arneEditor.getNetwork();
			
			// Command:
			AbstractTransactionalCommand command = new AbstractTransactionalCommand(arneEditor.getEditingDomain(), "Clear Activations", null) {
				@Override
				protected CommandResult doExecuteWithResult(
						IProgressMonitor monitor, IAdaptable info)
						throws ExecutionException {
					network.getActivations().clear();
					return CommandResult.newOKCommandResult();
				}
			};
			
			try {
				command.execute(new NullProgressMonitor(), null);
			} catch (ExecutionException e) {
				throw new RuntimeException(e);
			}
			
		}
	}
	
}
